import React, { useState, useMemo } from 'react';

function ExpensiveCalculation({ items, filter }) {
    const [sortOrder, setSortOrder] = useState('asc');

    // 使用 useMemo 缓存过滤和排序结果
    const processedItems = useMemo(() => {
        console.log('执行昂贵的计算...');

        // 模拟昂贵的计算过程
        const filtered = items.filter(item =>
            item.name.toLowerCase().includes(filter.toLowerCase())
        );

        const sorted = filtered.sort((a, b) => {
            if (sortOrder === 'asc') {
                return a.name.localeCompare(b.name);
            } else {
                return b.name.localeCompare(a.name);
            }
        });

        return sorted;
    }, [items, filter, sortOrder]); // 依赖数组

    return (
        <div>
            <button onClick={() => setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')}>
                排序: {sortOrder === 'asc' ? '升序' : '降序'}
            </button>
            <ul>
                {processedItems.map(item => (
                    <li key={item.id}>{item.name}</li>
                ))}
            </ul>
        </div>
    );
}

export default ExpensiveCalculation;